<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 封装一个函数，作用和axios一样
        function ajax({ method, url, params, data }) {
            return new Promise((resolve, reject) => {
                let arr = []
                for (let key in params) {
                    arr.push(`${key}=${params[key]}`)
                }
                const xhr = new XMLHttpRequest()
                xhr.addEventListener('load', function () {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        resolve(JSON.parse(xhr.response))
                    } else if (xhr.status >= 300) {
                        reject(JSON.parse(xhr.response))
                    }
                })
                xhr.open(method, url + '?' + arr.join('&'))
                if (typeof data === 'string') {
                    // 说明提交的是查询字符串
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
                    xhr.send(data)
                } else if (data instanceof FormData) {
                    // 说明提交的是FormDate
                    xhr.send(data)
                } else if (data instanceof Object) {
                    // 说明提交的是字面量对象
                    xhr.setRequestHeader('Content-Type', 'application/json')
                    xhr.send(JSON.stringify(data))
                } else {
                    xhr.send()
                }
            })
        }
        ajax({
            method: 'GET',
            url: 'http://www.itcbc.com:3006/api/getbooks',
            params: {
                appkey: 'xiaofeng'
            }
        }).then(res => {
            console.log(res)
        })

        ajax({
            method: 'POST',
            url: 'http://www.itcbc.com:3006/api/addbook',
            data: {
                bookname: '西游记',
                author: '吴承恩',
                publisher: '北京出版社',
                appkey: 'xiaofeng'
            }
        }).then(res => {
            console.log(res)
        })

    </script>
</body>

</html>